/**************************************************************
 *@ProjectName: blweibo
 *@FileName: ImageViewer.java
 *@Date: 2011-5-31
 *@Copyright: 2011 www.hrbanlv.com Inc. All rights reserved.
 **************************************************************/
package com.zhiweibo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.zhiweibo.util.HttpUtil;
import com.zhiweibo.util.Logger;

/**
 * The Class ImageViewer.
 * 
 * @author SunHaibin
 * @since Android 1.6
 * @history 2011-5-31
 */
public class ImageViewer extends Activity implements OnClickListener {

    /** The bt iv back. */
    private Button btIvBack;

    /** The bt iv save. */
    private Button btIvSave;

    /** The iv image. */
    private ImageView ivImage;

    /** The zc zooms. */
    private ZoomControls zcZooms;

    /** The ib turn left. */
    private ImageButton ibTurnLeft;

    /** The ib turn right. */
    private ImageButton ibTurnRight;

    /** The handler. */
    private Handler handler;

    /** The bm. */
    private Bitmap bm;

    /** The src height. */
    private int srcHeight;

    /** The src width. */
    private int srcWidth;

    /** The time. */
    private float time = 4.0f;

    /** The str url. */
    private String strUrl;

    /**
     * Instantiates a new image viewer.
     */
    public ImageViewer() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message paramMessage) {
                switch (paramMessage.what) {
                case 2:
                    if (zcZooms != null) {
                        zcZooms.setVisibility(4);
                    }
                    break;
                }
            }
        };
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.imageviewer);
        strUrl = getIntent().getStringExtra("picUrl");
        // lyIvTitle = (LinearLayout) findViewById(R.id.lyIvTitle);
        btIvBack = (Button) findViewById(R.id.btIvBack);
        btIvBack.setTextColor(Color.WHITE);
        btIvBack.setOnClickListener(this);
        // tvIvText = (TextView) findViewById(R.id.tvIvText);
        btIvSave = (Button) findViewById(R.id.btIvSave);
        btIvSave.setTextColor(Color.WHITE);
        btIvSave.setOnClickListener(this);
        btIvSave.setClickable(true);
        // imageContainer = (ScrollView) findViewById(R.id.imageContainer);
        ivImage = (ImageView) findViewById(R.id.ivImage);
        zcZooms = (ZoomControls) findViewById(R.id.zcZooms);
        zcZooms.setOnZoomInClickListener(new ZoomInClickListener());
        zcZooms.setOnZoomOutClickListener(new ZoomOutClickListener());
        // ibTurnButtons = (LinearLayout) findViewById(R.id.ibTurnButtons);
        ibTurnLeft = (ImageButton) findViewById(R.id.ibTurnLeft);
        ibTurnLeft.setOnClickListener(this);
        ibTurnRight = (ImageButton) findViewById(R.id.ibTurnRight);
        ibTurnRight.setOnClickListener(this);
        new FetchImage().execute(0);
        handler.sendEmptyMessageDelayed(2, 3000L);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        if (v == btIvBack) {
            finish();
        } else if (v == btIvSave) {
            File localFile1 = Environment.getExternalStorageDirectory();
            File path = new File(localFile1.getPath() + File.separator + "zhiweibo/pics");
            if (!path.exists()) {
                path.mkdirs();
            }
            File f = new File(path, "zhiweibo_img_" + System.currentTimeMillis() + ".jpg");
            try {
                FileOutputStream fOut;
                fOut = new FileOutputStream(f);
                bm.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                fOut.flush();
                fOut.close();
                Toast.makeText(this, getString(R.string.save_pic_ok, f.getPath()), Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                Logger.d(e);
                Toast.makeText(this, R.string.save_pic_failed, Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Logger.d(e);
                Toast.makeText(this, R.string.save_pic_failed, Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * Makesure zoom controls.
     */
    private void makesureZoomControls() {
        if (time == 1) {
            zcZooms.setIsZoomOutEnabled(false);
        } else {
            zcZooms.setIsZoomOutEnabled(true);
        }
        if (time == 16) {
            zcZooms.setIsZoomInEnabled(false);
        } else {
            zcZooms.setIsZoomInEnabled(true);
        }
    }

    /**
     * The listener interface for receiving zoomInClick events. The class that
     * is interested in processing a zoomInClick event implements this
     * interface, and the object created with that class is registered with a
     * component using the component's
     * <code>addZoomInClickListener<code> method. When
     * the zoomInClick event occurs, that object's appropriate
     * method is invoked.
     * 
     * @see ZoomInClickEvent
     */
    class ZoomInClickListener implements View.OnClickListener {

        /*
         * (non-Javadoc)
         * 
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View paramView) {
            time *= 2;
            Matrix matrix = new Matrix();
            matrix.postScale(time / 4, time / 4);
            Bitmap resizeBm = Bitmap.createBitmap(bm, 0, 0, srcWidth, srcHeight, matrix, true);
            ivImage.setImageBitmap(resizeBm);
            makesureZoomControls();
        }
    }

    /**
     * The listener interface for receiving zoomOutClick events. The class that
     * is interested in processing a zoomOutClick event implements this
     * interface, and the object created with that class is registered with a
     * component using the component's
     * <code>addZoomOutClickListener<code> method. When
     * the zoomOutClick event occurs, that object's appropriate
     * method is invoked.
     * 
     * @see ZoomOutClickEvent
     */
    class ZoomOutClickListener implements View.OnClickListener {

        /*
         * (non-Javadoc)
         * 
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View paramView) {
            time /= 2;
            Matrix matrix = new Matrix();
            matrix.postScale(time / 4, time / 4);
            Bitmap resizeBm = Bitmap.createBitmap(bm, 0, 0, srcWidth, srcHeight, matrix, true);
            ivImage.setImageBitmap(resizeBm);
            makesureZoomControls();
        }
    }

    /**
     * Inits the bitmap.
     */
    private void initBitmap() {
        ivImage.setImageBitmap(bm);
        if (bm != null) {
            srcHeight = bm.getHeight();
            srcWidth = bm.getWidth();
        } else {
            sendBroadcast(new Intent("com.hbr.weibo.noimage"));
            finish();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        zcZooms.setVisibility(View.VISIBLE);
        handler.sendEmptyMessageDelayed(2, 3000L);
        return super.onTouchEvent(event);
    }

    /**
     * The Class FetchImage.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class FetchImage extends AsyncTask<Object, Integer, Bitmap> {

        /** The pd. */
        private ProgressDialog pd;

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Bitmap doInBackground(Object... params) {
            return HttpUtil.getImage(ImageViewer.this, strUrl);
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Bitmap result) {
            bm = result;
            initBitmap();
            if (pd != null) {
                pd.dismiss();
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(ImageViewer.this);
            pd.setMessage("请稍候……");
            pd.show();
        }

    }
}
